import 'package:flutter/material.dart';
import 'dart:ui';
import 'package:lib_util/SPUtils.dart';
import '../../../generated/l10n.dart';
import '../../../main.dart';
import '../base/BaseWidget.dart';
import '../base/TitleBarWidget.dart';
import 'LanguageUtil.dart';

class LanguagePage extends StatefulWidget {
  const LanguagePage({super.key});

  @override
  State<LanguagePage> createState() => _LanguagePageState();
}

class _LanguagePageState extends State<LanguagePage> {
  String currentLocaleName = "";

  @override
  initState() {
    currentLocaleName = SPUtils.getLangCode(window.locale.languageCode);
    super.initState();
  }

  //切换语言
  changeLang(String localeName) {
    if (localeName != currentLocaleName) {
      SPUtils.setLangCode(localeName);
      currentLocaleName = localeName;
      var split = currentLocaleName.split("-");
      Locale local;
      if (split.length == 3) {
        local = Locale.fromSubtags(languageCode: split[0], scriptCode: split[1], countryCode: split[2]);
      } else {
        local = Locale(localeName);
      }
      runApp(MyApp(locale: local));
      setState(() {
        currentLocaleName = localeName;
      });
    }
  }

  Widget getLanguageList(int index) {
    Map<String, String> map = LanguageUtil.languageMap;
    var key = map.keys.elementAt(index);
    var value = map[key]!;
    bool isSelected = value == currentLocaleName;

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        changeLang(value);
      },
      child: Container(
        decoration: BoxDecoration(color: isSelected ?   Colors.blueGrey : Colors.transparent),
        margin: const EdgeInsets.only(bottom: 5),
        padding: const EdgeInsets.all(10),
        child: Stack(
          alignment: Alignment.center,
          children: [Text(key, style: TextStyle(color: isSelected ? Colors.black : Colors.black, fontSize: 20))],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return BaseWidget(
      child: Column(
        children: [
          TitleBarWidget(title: S.of(context).str_id_38),
          Expanded(
            child: ListView.builder(
              scrollDirection: Axis.vertical,
              shrinkWrap: true,
              itemCount: LanguageUtil.languageMap.length,
              itemBuilder: (context, index) {
                return getLanguageList(index);
              },
            ),
          ),
        ],
      ),
    );
  }
}
